﻿using ProjScan.Modules;
using ProjScan.Tools;
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEngine;

namespace ProjScan.ScanGUI.Tools
{
    //
    // 摘要:
    //     文件树视图 - Class26
    internal class FileTreeView : TreeView
    {
        private readonly List<TreeViewItem> _items;

        private TreeViewItem _root;

        private Dictionary<string, FailedAssetInfo> _assets;

        private string _ruleId;

        private string _ruleName;

        private Module _module;

        private bool _isFixedRes;

        private bool _isMainUI;

        private WhiteWindow _whiteWindow;

        public FileTreeView(TreeViewState state, MultiColumnHeader header, string ruleId, string ruleName, Module module, bool mu, bool fr)
            : base(state, header)
        {
            _items = new List<TreeViewItem>();
            _root = new TreeViewItem(-1, -1, "root");
            _ruleId = ruleId;
            _ruleName = ruleName;
            _module = module;
            _isMainUI = mu;
            _isFixedRes = fr;
            base.rowHeight = 20f;
            Reload();
        }

        protected override TreeViewItem BuildRoot()
        {
            return _root;
        }

        protected override IList<TreeViewItem> BuildRows(TreeViewItem treeViewItem)
        {
            _items.Clear();
            AddItems(_ruleId);
            TreeView.SetupParentsAndChildrenFromDepths(treeViewItem, _items);
            return _items;
        }

        public void RefreshRows()
        {
            BuildRows(_root);
        }

        protected void AddItems(string ruleId)
        {
            if (!FailedResultManager.Instance.dicFails.ContainsKey(ruleId))
            {
                return;
            }

            _assets = FailedResultManager.Instance.dicFails[ruleId];
            int num = 0;
            foreach (KeyValuePair<string, FailedAssetInfo> asset in _assets)
            {
                _items.Add(new TreeViewItem(num++, 0, asset.Key));
            }
        }

        private void DrawCell(Rect rect, TreeViewItem item, int column)
        {
            string displayName = item.displayName;
            switch (column)
            {
                case 0:
                    if (GUI.Button(rect, item.displayName, Singleton<GUIStyleManager>.Instance.GetTStyle(TStyle.AssetBar)))
                    {
                        ToolsHelper.SelectionObject(item.displayName, _module);
                    }

                    break;
                case 1:
                    if (!_isFixedRes || _isMainUI)
                    {
                        if (_isMainUI)
                        {
                            char[] separator = new char[1]
                            {
                            '$'
                            };
                            if (WhiteAssetManager.Instance.GetWhiteListForRuleId(_ruleId).Contains(displayName.Split(separator)[0]))
                            {
                                _assets[displayName].ShouldBeFixed = EditorGUI.Toggle(LayOutUtils.GetToggleRect(rect), value: false, Singleton<GUIStyleManager>.Instance.GetTStyle(TStyle.CheckBox));
                            }
                            else
                            {
                                _assets[displayName].ShouldBeFixed = EditorGUI.Toggle(LayOutUtils.GetToggleRect(rect), _assets[displayName].ShouldBeFixed, Singleton<GUIStyleManager>.Instance.GetTStyle(TStyle.CheckBox));
                            }
                        }
                        else
                        {
                            _assets[displayName].ShouldBeFixed = false;
                        }
                    }
                    else
                    {
                        DrawAddButton(rect, _ruleId, displayName, _whiteWindow);
                    }

                    break;
                case 2:
                    {
                        GUIStyle basicStyle = Singleton<GUIStyleManager>.Instance.GetBasicStyle(TBasicStyle.label);
                        basicStyle.fontSize = 13;
                        basicStyle.alignment = TextAnchor.MiddleCenter;
                        EditorGUI.LabelField(rect, _assets[item.displayName].IsFixed.ToString(), basicStyle);
                        break;
                    }
                case 3:
                    DrawAddButton(rect, _ruleId, displayName, _whiteWindow);
                    break;
            }
        }

        private static void DrawAddButton(Rect rect, string label, string path, WhiteWindow whiteWindow)
        {
            string text = path.Split(new char[1]
            {
                '$'
            })[0];
            GUIStyle gUIStyle = new GUIStyle(GUI.skin.button);
            gUIStyle.fontSize = 14;
            gUIStyle.fixedWidth = 75f;
            gUIStyle.alignment = TextAnchor.MiddleRight;
            if (WhiteAssetManager.Instance.GetWhiteListForRuleId(label).Contains(text))
            {
                GUI.Label(rect, "已添加", gUIStyle);
            }
            else if (GUI.Button(rect, "添加[ + ]", gUIStyle))
            {
                WhiteAssetManager.Instance.AddEntry(label, text);
                if (whiteWindow != null)
                {
                    whiteWindow.UpdateWhiteList();
                    whiteWindow.Repaint();
                }
            }
        }

        private WhiteWindow OpenWhiteListPage(Module module, string filePath, string inputPath)
        {
            GUILayout.BeginHorizontal();
            EditorGUILayout.Space();
            if (!GUILayout.Button("开启白名单页面", GUILayout.Width(400f)))
            {
                GUILayout.EndHorizontal();
                return _whiteWindow;
            }

            if (_whiteWindow == null)
            {
                _whiteWindow = ScriptableObject.CreateInstance<WhiteWindow>();
                _whiteWindow.init(module, filePath, inputPath);
                _whiteWindow.minSize = new Vector2(570f, 510f);
                _whiteWindow.Show();
            }
            else
            {
                _whiteWindow.Focus();
            }

            GUILayout.EndHorizontal();
            return _whiteWindow;
        }

        public bool IsResultEmpty()
        {
            return _assets == null || _assets.Count == 0;
        }

        public override void OnGUI(Rect rect_0)
        {
            if (_isFixedRes)
            {
                OpenWhiteListPage(_module, _ruleName, _ruleId);
            }

            base.OnGUI(rect_0);
        }

        protected override void RowGUI(RowGUIArgs rowGUIArgs_0)
        {
            TreeViewItem item = rowGUIArgs_0.item;
            for (int i = 0; i < rowGUIArgs_0.GetNumVisibleColumns(); i++)
            {
                DrawCell(rowGUIArgs_0.GetCellRect(i), item, rowGUIArgs_0.GetColumn(i));
            }
        }

        public static MultiColumnHeaderState CreateMultiColumnHeaderState(float float_0, bool bool_2, bool bool_3)
        {
            FailedDataHeaderColumn[] array = new FailedDataHeaderColumn[1]
            {
                new FailedDataHeaderColumn
                {
                    type = FailedDataHeaderColumn.ColumnType.assetName,
                    headerContent = new GUIContent("资源位置"),
                    headerTextAlignment = TextAlignment.Left,
                    sortedAscending = false,
                    sortingArrowAlignment = TextAlignment.Center,
                    width = 400f,
                    minWidth = 60f,
                    autoResize = true,
                    allowToggleVisibility = false,
                    canSort = false
                }
            };
            if (bool_2)
            {
                int num = array.Length;
                Array.Resize(ref array, num + 2);
                array[num] = new FailedDataHeaderColumn
                {
                    type = FailedDataHeaderColumn.ColumnType.shouldBeFixed,
                    headerContent = new GUIContent("是否修复", "是否在此资源中修复此规则"),
                    headerTextAlignment = TextAlignment.Center,
                    sortedAscending = false,
                    sortingArrowAlignment = TextAlignment.Left,
                    width = 90f,
                    minWidth = 60f,
                    maxWidth = 90f,
                    autoResize = false,
                    canSort = false
                };
                array[num + 1] = new FailedDataHeaderColumn
                {
                    type = FailedDataHeaderColumn.ColumnType.isFixed,
                    headerContent = new GUIContent("已修复（？）", "此资源在当前规则中是否已修复"),
                    headerTextAlignment = TextAlignment.Center,
                    sortedAscending = false,
                    sortingArrowAlignment = TextAlignment.Left,
                    width = 100f,
                    minWidth = 100f,
                    maxWidth = 100f,
                    autoResize = false,
                    allowToggleVisibility = true,
                    canSort = false
                };
            }

            if (bool_3)
            {
                int num2 = array.Length;
                Array.Resize(ref array, num2 + 1);
                array[num2] = new FailedDataHeaderColumn
                {
                    type = FailedDataHeaderColumn.ColumnType.shouldInWhiteList,
                    headerContent = new GUIContent("加入白名单", "此资源是否已在白名单中"),
                    headerTextAlignment = TextAlignment.Center,
                    sortedAscending = false,
                    sortingArrowAlignment = TextAlignment.Left,
                    width = 90f,
                    minWidth = 90f,
                    maxWidth = 90f,
                    autoResize = false,
                    canSort = false
                };
            }

            MultiColumnHeaderState.Column[] columns = array;
            return new MultiColumnHeaderState(columns);
        }
    }
}